<template>
  <div>
    <el-switch
      v-if="isLoad"
      ref="switchRef"
      :model-value="modelValue"
      inline-prompt
      :disabled="disabled"
      :active-text="activeText"
      :inactive-text="inactiveText"
      :active-value="activeValue"
      :inactive-value="inactiveValue"
      :loading="loading"
      :before-change="beforeChange"
      @change="change"
    />

    <ele-popconfirm
      v-if="!disabled && !beforeDisabled"
      :width="width"
      title="提示"
      placement="top-end"
      virtual-triggering
      :virtual-ref="switchRef"
      @confirm="onConfirm"
      @cancel="onCancel"
    >
      <template #content>
        <div>确定设置此项为：<span class="font-semibold" :class="modelValue === activeValue ? 'text-[var(--el-color-danger)]' : 'text-[var(--el-color-primary)]'">{{ modelValue === activeValue ? (inactiveText || '停用') : (activeText || '启用') }}</span> ？</div>
      </template>
    </ele-popconfirm>
  </div>
</template>

<script setup>
import { message } from '@/utils/index'
import { onMounted, ref } from 'vue'

const props = defineProps({
  modelValue: {
    type: [Boolean, String, Number],
  },
  width: {
    type: [String, Number],
    default: 220,
  },
  beforeDisabled: {
    type: Boolean,
    default: false,
  },
  disabled: {
    type: Boolean,
    default: false,
  },
  activeValue: {
    type: [Boolean, String, Number],
    default: 1,
  },
  inactiveValue: {
    type: [Boolean, String, Number],
    default: 2,
  },
  activeText: {
    type: String,
    default: '',
  },
  inactiveText: {
    type: String,
    default: '',
  },
  done: {
    type: Function,
  },
})

const emit = defineEmits(['update:modelValue', 'done'])

const loading = ref(false)

const switchRef = ref()

let confirmResult

const isLoad = ref(false)

onMounted(() => {
  isLoad.value = true
})

async function beforeChange() {
  if (props.disabled || props.beforeDisabled)
    return true

  return await new Promise((resolve) => {
    confirmResult = resolve
  })
}

function onConfirm() {
  confirmResult(true)
}

function onCancel() {
  confirmResult(false)
}

function change(value) {
  if (!props.done
    || ![props.activeValue, props.inactiveValue].includes(value)
    || ![props.activeValue, props.inactiveValue].includes(props.modelValue)) {
    return
  }

  loading.value = true
  props.done(value).then((res) => {
    message(res.msg, res.success)
    if (res.success)
      emit('update:modelValue', value)
  }).finally(() => loading.value = false)
}
</script>

<style lang="scss" scoped>

</style>
